<?php

namespace App\Library\Console\Commands;

use App\Imports\DemoImport;
use Illuminate\Console\Command;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\HeadingRowImport;

class DemoImportCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:demo-import';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * handle
     * @return void
     */
    public function handle(): void
    {
        $realpath = public_path('demo-import.xlsx');
        $headings = (new HeadingRowImport())->toArray($realpath);
        $head = DemoImport::head();
        foreach ($head as $header) {
            if (!in_array($header, $headings[0][0])) {
                dd('模板表头不对,正确的模板表头应该是:' . implode(',', $head));
            }
        }
        /*
         * 如果是前端传文件 那么
         * $file = $request->file('file_name');
         * Excel::import(new DemoImport, $file);
         * 下面是 $realpath
         * if(substr(strtolower(PHP_OS), 0, 3) == 'win') {
                //获取文件临时目录 windows环境
                $realpath = $file->getRealPath();
            } else {
                //获取文件临时目录 linux环境
                $realpath = storage_path('app') . '/' . $file->store('temp');
            }
         */
        Excel::import(new DemoImport, $realpath);
    }
}
